package cn.etynit.order.rocketmq;

import cn.etynit.basic.config.BussinessException;
import cn.etynit.order.domain.OrderPetAcquisition;
import cn.etynit.order.service.IOrderPetAcquisitionService;
import cn.etynit.pet.domain.SearchMasterMsg;
import cn.etynit.pet.service.ISearchMasterMsgService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
 * 消费者，消费了消息就修改订单状态
 */
@Component
@RocketMQMessageListener(consumerGroup = "petome_consumer_group", topic = "petome_topic")
public class pethomrConsumer implements RocketMQListener<String> {

    @Autowired
    private ISearchMasterMsgService searchMasterMsgService;

    @Autowired
    private IOrderPetAcquisitionService orderPetAcquisitionService;

    @Override
    public void onMessage(String message) {
        // 若在30s内接到用户订单，回到寻主池
        System.out.println("消费者消费消息:" + message);
        // 校验参数
        if (message == null) {
            throw new BussinessException("该订单不存在！");
        }
        // 根据订单编号查询订单
        OrderPetAcquisition orderPetAcquisition = orderPetAcquisitionService.findByOrderSn(Long.valueOf(message));
        if (orderPetAcquisition == null){
            throw new BussinessException("该订单不存在！");
        }
        // 若订单状态是0，证明该订单未处理，直接取消该订单
        if(orderPetAcquisition.getState() == 0){
            // 修改订单状态为取消
            orderPetAcquisition.setState(-1);
            // 更新订单
            orderPetAcquisitionService.update(orderPetAcquisition);
            // 查询相对应的寻主消息。把消息返回寻主池
            SearchMasterMsg msg = searchMasterMsgService.findById(orderPetAcquisition.getSearchMasterMsgId());
            if (msg == null){
                throw new BussinessException("该寻主不存在！");
            }
            // 置空shopId，状态改为1，待审核
            msg.setShopId(null);
            msg.setState(1);
            // 更新寻主消息
            searchMasterMsgService.update(msg);
            // todo 添加接单超时日志表
        }
    }
}
